package com.pi.shisan.component.impl;

import com.pi.shisan.common.NumberUtil;
import com.pi.shisan.component.BaseAbstractComponent;
import com.pi.shisan.component.util.ComponentThread;
import com.pi.shisan.component.util.FastIntList;
import com.pi.shisan.component.util.SharedSource;
import com.pi.shisan.util.DefaultFont8x8;
import com.pi.shisan.util.spipoint.DataWriter;
import com.pi.shisan.util.spipoint.MultipleXyToSpiConverter;
import lombok.extern.slf4j.Slf4j;

import static com.pi.shisan.component.util.SharedMethod.drawPoints;

/**
 * 时间组件
 */
@Slf4j
public class TimeFormatComponent extends BaseAbstractComponent {

    /**
     * 冒号缓存
     */
    private int[] colon = DefaultFont8x8.getPointsAsXy(DefaultFont8x8.SIGN_SMALL_COLON);

    /**
     * 上一次绘制过的所有点保存
     */
    private final FastIntList lastAllPoints = new FastIntList();

    /**
     * 组件内容坐标X
     */
    private int fromX;
    /**
     * 组件内容坐标Y
     */
    private int fromY;

    /**
     * 秒为单位。
     */
    private int val;

    public TimeFormatComponent(MultipleXyToSpiConverter spi, DataWriter dataWriter) {
        super(spi,dataWriter);
    }

    public void setVal(int val) {
        this.val = val;
        doRefresh(val);
    }

    @Override
    public void refresh() {
        ComponentThread.execute(()->{
            try {
                doRefresh(val);
            } catch (Exception e) {
                log.error("时间格式化组件刷新失败：",e);
            }
        });
    }

    private void doRefresh(int val) {
        int minute = val / 60;
        int seconds = val % 60;

        int x = fromX;
        int y = fromY;
        lastAllPoints.forEach(spi::delete);
        //修复这个家伙可能带来的内存溢出问题（之前都没做过clear...）
        lastAllPoints.clear();
        int maxY = Short.MIN_VALUE;
        for (int i = 1; i >= 0; i--) {
            int maxX = Integer.MIN_VALUE;
            int[] numPoints = SharedSource.getFromNumCache(NumberUtil.getSimpleNum(minute, i));
            int max = drawPoints(numPoints,startX, startY, x, y, maxX,maxY, width, height, spi, lastAllPoints);
            maxX = NumberUtil.toX(max);
            maxY = NumberUtil.toY(max);
            x += maxX + 2;
        }
        if ((seconds & 1) == 1) {
            drawPoints(colon,startX, startY, x, y, Integer.MIN_VALUE,maxY, width, height, spi, lastAllPoints);
        }
        x += 1 + 1;
        for (int i = 1; i >= 0; i--) {
            int maxX = Integer.MIN_VALUE;
            int[] numPoints = SharedSource.getFromNumCache(NumberUtil.getSimpleNum(seconds, i));
            int max = drawPoints(numPoints,startX, startY, x, y, maxX,maxY, width, height, spi, lastAllPoints);
            maxX = NumberUtil.toX(max);
            maxY = NumberUtil.toY(max);
            x += maxX + 2;
        }
        flushData();
    }
}
